<template>
  <div style="display: flex">
    <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;min-width:64px" class="primary">{{$route.meta.title}}</span>
          </div>
          <div class="report_header_left"></div>
          <div class="report_header_query" style="width: 120px">
            <query-status @queryStatus='queryStatus' :status="query.status" :value="query.value" ></query-status>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="请输入公司名称" v-model="keyword" clearable></el-input>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;"  size="small" type="primary" v-permission="['customer.query']"
                       @click="queryClick">查询</el-button>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary"  v-permission="['customer.add']"
                       @click="addClick">新增</el-button>

          </div>
        </div>
      </el-header>
      <div class="pd10">

        <el-table
          :data="customerList"
          border
          stripe
          :height="curHeight"
          v-loadMore="[payLoads,'company-list-table']"
          ref="table"
          style="width: 100%;"
        >
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center"
          >
          </el-table-column>
          <el-table-column label="logo" prop="logo" align="center" width="80">
            <template slot-scope="scope">
              <img :src="scope.row.logo" style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;"></img>
              <!--<el-image :src="scope.row.logo"/>-->
            </template>
          </el-table-column>
          <el-table-column label="公司名称" prop="name"></el-table-column>
          <!--          <el-table-column label="公司类型" prop="type" align="center" width="80"></el-table-column>-->
          <!--          <el-table-column label="企业ID" align="center" prop="id"width="80"></el-table-column>-->
          <el-table-column label="联系人"    prop="linkman" align="center" width="110"></el-table-column>
          <el-table-column label="联系电话"  prop="phone"   align="center" width="110"></el-table-column>
          <el-table-column label="详情地址"  prop="address" ></el-table-column>

          <el-table-column
            label="客户类型"
            prop="type"
            width="130"
            align="center">
            <template slot-scope="scope">
<!--              <el-tag>-->
                <span>{{scope.row.type | watchType}}</span>
<!--              </el-tag>-->
            </template>
          </el-table-column>
          <!--<el-table-column label="管理员"   prop="userName" align="center" width="80"></el-table-column>-->
          <!--          <el-table-column label="审核资料" prop="meta" ></el-table-column>-->
          <!--<el-table-column label="审核说明" prop="msg" ></el-table-column>-->
          <el-table-column
            label="状态"
            prop="status"
            width="80"
            align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.status ==0 " >
                <el-tag :type="scope.row.status == 0?'info':'success'">
                  <span>{{scope.row.status | watchStatus}}</span>
                </el-tag>
              </div>
              <div v-else >
                <el-tag :type="scope.row.status == 2?'warning':'success'">
                  <span>{{scope.row.status | watchStatus}}</span>
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="功能" fixed="right" width="80" align="center">
            <template slot-scope="scope">
              <el-tooltip  class="item" effect="dark" content="详情"  v-permission="['customer.detail']"
                           placement="top-start">
                <el-button @click="detailClick(scope.row)" type="primary" size="mini"
                >详情</el-button>
              </el-tooltip>
              <!--<el-tooltip  class="item" effect="dark" content="审核" placement="top-start" v-if="scope.row.status == 0">-->
                <!--<el-button :loading="loading"  @click="update(scope.row)" type="primary" size="mini">审核</el-button>-->
              <!--</el-tooltip>-->
              <!--<el-tooltip  class="item" effect="dark" content="驳回" placement="top-start" v-if="scope.row.status == 0">-->
                <!--<el-button :loading="loading" @click="update(scope.row)" type="warning" size="mini">驳回</el-button>-->
              <!--</el-tooltip>-->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="scope">
              <!--              v-permission="['company.edit']"-->

              <div>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="修改客户"
                  v-permission="['customer.edit']"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <!--                v-permission="['company.del']"-->

                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除客户"
                  v-permission="['customer.del']"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a style="margin-left: 10px" @click="deleteCustomer(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="loadCustomer"
        ></pagination>
      </el-footer>
    </el-container>
    <el-dialog
      title="驳回请求"
      :visible.sync="isShow"
      width="40%"
      left>
      <div style="display: flex; flex-direction: column; justify-content: center;align-items: stretch;font-size: 15px; line-height: 30px;padding: 0 5vw">
        <div style="display: flex; flex-direction: row; justify-content: center; align-items: center;font-size: 15px; line-height: 30px;margin:0">
          <span style="width:120px;letter-spacing:6px;text-align: center;padding-left: 3px;">审核说明:</span>
          <el-input style="height: 90%" v-model="customerOpenForm.msg"  clearable placeholder="请输入驳回原因"></el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning"  :loading="loading" v-permission="['customer.auth']" @click="rejectClick">驳回</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<style scoped>
</style>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list, del, update } from "@/api/customer";
import { EventBus } from "@/api/eventBus";
import Pagination from "@/components/Pagination";
import loadMore from "@/utils/loadMore.js";
import utils from "@/utils/utils";
import queryApartment from '@/components/Query/queryGroup'
import queryStatus from "@/components/Query/queryStatus";
export default {
  name: "customer-list",
  directives: { permission, loadMore },
  data() {
    return {
      bindingImage:'',
      customerList:[],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      query: {
        id:this.$route.query.id,
        status: '',
        value:"",
      },
      keyword: "",
      curHeight: null,
      groupName: this.$route.query.groupName,
      groupId: this.$route.query.groupId,
      companyId: this.$route.query.companyId,
      companyName: this.$route.query.companyName,
      deleted: false,
      payLoads: '',
      customerOpenForm: {
        id: '',
        status: '',
        msg:""
      },
      isShow:false,
      loading :false
    };
  },
  components: {queryApartment, Pagination,queryStatus},
  created() {
    this.loadCustomer();
    EventBus.$on("customer-add", res => {
      this.customerList.splice(0, 0, res);
    });

    EventBus.$on("customer-edit", res => {
      for (var i = 0; i < this.customerList.length; i++) {
        if (this.customerList[i].id == res.id) {
          this.$set(this.customerList, i, res)
        }
      }
    });
    EventBus.$on("customer-detail", res => {
      for (var i = 0; i < this.customerList.length; i++) {
        if (this.customerList[i].id == res.id) {
          this.$set(this.customerList, i, res)
        }
      }
    });
  },
  activated() {
    this.payLoads = new Date().getTime();
  },
  mounted() {
    this.comeIn();
    this.beforeMount();
  },
  filters: {
    formatDate: function(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    },
    watchStatus(val) {
      if (val == 1) {
        return '已认证'
      }
      if (val == 2) {
        return '已驳回'
      } else {
        return '未认证'
      }
    },
    watchType(val) {
      if (val == 1) {
        return '供货商'
      } else {
        return '采购方'
      }
    },
  },
  watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
    status(newVal, oldVal) {
      this.form.status = newVal;
    },
    openLoading(newVal, oldVal){
      this.loading = newVal;
    },
  },
  methods: {

    loadCustomer() {
      var _this = this;
      let params = new URLSearchParams();
      params.append("pageNum", _this.pageNum);
      params.append("pageSize", _this.pageSize);
      params.append("status", _this.query.status);
      params.append("keyword", _this.keyword);
      params.append("deleted", _this.deleted);
      list(params).then(response => {
        console.info(response.data,1111)
        let list=response.data.data;
        _this.customerList = _this.formatList(list);
        _this.total = response.data.total;
        this.updateScroll();
      })
    },
    chooseClick() {
      this.queryType = !this.queryType;
      if (this.queryType == false) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 266; //减去页面上固定高度height
      } else {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220; //减去页面上固定高度height
      }
    },
    deleteCustomer(data) {
      console.log("data" + JSON.stringify(data));
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(data.id)
            .then(response => {
              _this.customerList.forEach(function(item, index) {
                if (item.id === data.id) {
                  _this.customerList.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            })
            .catch(error => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },
    queryClick() {
      this.pageNum = 1;
      this.loadCustomer();
    },
    queryStatus(item){
      // console.log("选择状态",item)
      this.query.status = item.status
      this.query.value = item.value
      // this.status = this.query.value
      console.log("选择状态",this.query.value,this.query.status)
    },
    // queryApartmentClick(item){
    //   this.query.buildingId = item.shopId
    //   this.query.buildingName = item.name
    //   this.buildingId = this.query.buildingId
    // },
    // queryCommunityClick(item){
    //   this.query.communityId = item.shopId
    //   this.query.communityName = item.name
    //   this.communityId = this.query.communityId
    // },
    resetClick() {
      this.query.companyId="";
      this.query.companyName="";
      this.query.groupId="";
      this.query.groupName="";
      this.query.value="";
      this.query.status='';
      this.keyword ="";
      this.pageNum = 1;
      this.loadCustomer();
    },

    dialogOpen () {
      this.isShow = true;
      this.customerOpenForm.msg = ""
    },

    //驳回
    rejectClick(){
      var _this = this
      _this.customerOpenForm.status = 2
      _this.customerOpenForm.msg =  this.customerOpenForm.msg
      _this.customerOpenForm.status = parseInt(this.customerOpenForm.status)
      if (_this.customerOpenForm.msg !==""){
        update(_this.customerOpenForm).then( res => {
          console.log(res, 'item');
          _this.customerList.forEach(function (item) {
            if (item.id == res.data.id) {
              item.status = res.data.status
              item.msg = res.data.msg
            }
          });
          _this.isShow = false;
          this.$message({
            message: res.content,
            offset: 120,
            center: true
          })
        })
      }else {
        this.$message({
          message: "驳回原因不能为空",
          offset: 120,
          center: true,
          type:"error"
        });
      }
    },

    //审核
    update(row) {
      var _this = this
      row.openLoading = true
      console.log(row,'row');
      this.customerOpenForm.id = row.id;
      if (row.status == 0 || row.status == 2) {
        this.customerOpenForm.status = 1
        this.customerOpenForm.msg = ""
        this.customerOpenForm.status = parseInt(this.customerOpenForm.status)
        update(_this.customerOpenForm).then(res=> {
          if(res.type == "success"){
            console.log('customerOpenForm',res)
            _this.customerList.forEach(function (item) {
              if (item.id == row.id){
                item.status = res.data.status
                item.msg = res.data.msg
              }
            })
            row.openLoading = false
            _this.$message({
              message: res.content,
              offset: 120,
              center: true
            });
          }
        }).catch(error => {
          row.openLoading = false
          console.log('error!!')
        });
      } else if (row.status == 1) {
        this.dialogOpen();
      }

    },

    detailClick(row) {
      this.$router.push({
        path: "/customer/detail",
        query: { id: row.id }
      });
    },
    //编辑企业信息
    editClick(row) {
      this.$router.push({
        path: "/customer/edit",
        query: { id: row.id }
      });
    },
    addClick() {
      this.$router.push({
        path: "/customer/add",
      });
    },
    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 266; //减去页面上固定高度height
          } else {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 220; //减去页面上固定高度height
          }
        })();
      };
    },
    comeIn() {
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - 220; //减去页面上固定高度height
    },
    //过滤企业列表
    formatDate2Day(val) {
      if(val){
        let date = new Date(val);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let d = date.getDate();
        d = d < 10 ? "0" + d : d;
        return y + "-" + MM + "-" + d;
      }else{
        return ""
      }
    },
    formatDate2Time(val) {
      if(val){
        let date = new Date(val);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let d = date.getDate();
        d = d < 10 ? "0" + d : d;
        let h = date.getHours();
        h = h < 10 ? "0" + h : h;
        let m = date.getMinutes();
        m = m < 10 ? "0" + m : m;
        let s = date.getSeconds();
        s = s < 10 ? "0" + s : s;
        return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
      }else{
        return ""
      }
    },
    formatList(data) {
      if (data.length > 0) {
        data.map(item => {
          item.createDate = this.formatDate2Day(item.createDate);
          item.modifyDate = this.formatDate2Time(item.modifyDate);
          item.rechangeDate = this.formatDate2Time(item.rechangeDate);
        });
      }
      return data;
    },

    updateScroll() {
      window.sessionStorage.setItem("loadTopcompany-list-table", 0);
      window.sessionStorage.setItem("loadLeftcompany-list-table", 0);
    }
  }
};
</script>

<style scoped>
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #f2f2f2;
}
/deep/.el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}
.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}
.report_header_left {
  width: 5px;
  height: 100%;
  background-color: #409EFF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_query {
  margin-left: 10px;
  width: 180px;
  margin-top: 5px;
}
</style>
